/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package marketrmi;

import id2212.homework2.ClientInter;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author yann
 */
public class AccountClient extends UnicastRemoteObject implements marketrmi.AccountClientInter {

    private Market market;
    private ClientInter clientRef;// The reference to the client for callBack
    private String clientName;
    private String marketPassword;
    private String bankPassword;
    private int nbSoldItem;
    private int nbBoughtItem;
    private List<Item> sellList;
    private String notification;
    private Statement sqlStatement;
    private static final String DATASOURCE = "marketbdd";

    private Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("DRIVER OK ! ");
        Connection connec = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/" + DATASOURCE, "root", "");
        System.out.println("Connection success !");
        return connec;
    }


    public AccountClient(String clientName, String passwordMarket, ClientInter cl, Market market) throws RemoteException {
        this.market = market;
        this.clientRef = cl;
        this.clientName = clientName;
        this.marketPassword = passwordMarket;
        this.sellList = new ArrayList<Item>();

        try {
            Connection connection;
            connection = getConnection();
            sqlStatement = connection.createStatement();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        // check if the client already exist and insert it in the DB if not
        ResultSet result = null;
        try {
            result = sqlStatement.executeQuery("SELECT * from client WHERE name='" + clientName + "'");

            if (!result.next()) { // here we have a new client
                result.close();
                sqlStatement.executeUpdate("INSERT INTO client VALUES(0,'" + clientName + "','" + passwordMarket + "','undef',0,0)");
            } else { // we need to get the sell List
                this.nbBoughtItem = result.getInt("nbBoughtItem");
                this.nbSoldItem = result.getInt("nbSoldItem");
                this.marketPassword = result.getString("marketPassword");
                this.bankPassword = result.getString("passwordBank");
                result = sqlStatement.executeQuery("SELECT * FROM item WHERE sellerName='" + clientName + "'");
                while (result.next()) {
                    Item item = new Item(result.getInt("id"), result.getString("name"), result.getInt("price"),
                            result.getInt("amount"), clientName, result.getString("passwordMarket"), this);
                    sellList.add(item);
                }
            }
            result.close();
        } catch (SQLException ex) {
            System.out.println(ex + " Unable to new account(name,pass,client)");
        }
    }

    public AccountClient(String clientName, String password, Market market) throws RemoteException {
        this.market = market;
        this.clientName = clientName;
        this.marketPassword = password;
        this.sellList = new ArrayList<Item>();

        try {
            Connection connection;
            connection = getConnection();
            sqlStatement = connection.createStatement();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        // check if the client already exist and insert it in the DB if not
        ResultSet result = null;
        try {
            result = sqlStatement.executeQuery("SELECT * from client WHERE name='" + clientName + "'");
            if (result.next()) {
                this.nbBoughtItem = result.getInt("nbBoughtItem");
                this.nbSoldItem = result.getInt("nbSoldItem");
                this.bankPassword = result.getString("passwordBank");
                result = sqlStatement.executeQuery("SELECT * FROM item WHERE sellerName='" + clientName + "'");
                while (result.next()) {
                    Item item = new Item(result.getInt("id"), result.getString("name"), result.getInt("price"),
                            result.getInt("amount"), clientName,bankPassword, this);
                    sellList.add(item);
                }
            }
            result.close();
        } catch (SQLException ex) {
            System.out.println(ex + " Unable to new account(name,pass)");
        }
    }

    public AccountClient(String clientName, Market market) throws RemoteException {
        this.market = market;
        this.clientName = clientName;
        this.sellList = new ArrayList<Item>();

        try {
            Connection connection;
            connection = getConnection();
            sqlStatement = connection.createStatement();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        // check if the client already exist and insert it in the DB if not
        ResultSet result = null;
        try {
            result = sqlStatement.executeQuery("SELECT * from client WHERE name='" + clientName + "'");
            if (result.next()) {
                this.nbBoughtItem = result.getInt("nbBoughtItem");
                this.nbSoldItem = result.getInt("nbSoldItem");
                this.bankPassword = result.getString("passwordBank");
                this.marketPassword = result.getString("passwordMarket");
                result.close();
                result = sqlStatement.executeQuery("SELECT * FROM item WHERE sellerName='" + clientName + "'");
                while (result.next()) {
                    Item item = new Item(result.getInt("id"), result.getString("name"), result.getInt("price"),
                            result.getInt("amount"), clientName,bankPassword,this);
                    sellList.add(item);
                }
            }

            result.close();
        } catch (SQLException ex) {
            System.out.println(ex + " Unable to create a new account");
        }
    }

    public synchronized void del() {
        System.out.println("Ask to delete");
        ResultSet result = null;
        try {
            sqlStatement.executeUpdate("DELETE FROM client WHERE name='" + clientName + "'");
            result.close();
        } catch (SQLException ex) {
            Logger.getLogger(AccountClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized void sell(String itemName, int price, int amount, String sellerBankPassword) {
        try {
            bankPassword = sellerBankPassword;
            Item sellItem = new Item(0, itemName, price, amount, clientName, bankPassword, this);
            this.sellList.add(sellItem);

            System.out.println("Client :" + this.clientName + " Sell: " + sellItem);
        } catch (RemoteException ex) {
            Logger.getLogger(AccountClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized String getClientName() {
        return clientName;
    }

    public synchronized List<Item> getSellList() {
        return sellList;
    }

    public synchronized ClientInter getClientRef() {
        return clientRef;
    }

    public synchronized void setClientRef(ClientInter clientRef) {
        this.clientRef = clientRef;
    }

    public synchronized void wish(ItemInter itemRef, int wishPriceMax) {
        /*
        try {
        Wish wishItem = new Wish(itemRef, wishPriceMax);
        //this.wishList.add(wishItem);
        
        System.out.println("Client :" + this.clientName + " Wish: " + wishItem);
        } catch (RemoteException ex) {
        Logger.getLogger(AccountClient.class.getName()).log(Level.SEVERE, null, ex);
        }
         * 
         */
    }

    @Override
    public synchronized void setNotificationString(String str) throws RemoteException {
        notification = str;
    }

    @Override
    public synchronized String getNotificationString() throws RemoteException {
        return notification;
    }

    public synchronized int getNbBoughtItem() {
        return nbBoughtItem;
    }

    public synchronized void setNbBoughtItem(int nbBoughtItem) {
        this.nbBoughtItem = nbBoughtItem;

        try {
            sqlStatement.executeUpdate("UPDATE client SET nbBoughtItem='" + nbBoughtItem + "' WHERE name='" + clientName + "'");
        } catch (SQLException ex) {
            Logger.getLogger(AccountClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public synchronized int getNbSoldItem() {
        return nbSoldItem;
    }

    @Override
    public synchronized void setNbSoldItem(int nbSoldItem) {
        this.nbSoldItem = nbSoldItem;

        try {
            sqlStatement.executeUpdate("UPDATE client SET nbSoldItem='" + nbSoldItem + "' WHERE name='" + clientName + "'");
        } catch (SQLException ex) {
            Logger.getLogger(AccountClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public synchronized String getMarketPassword() throws RemoteException {
        ResultSet result = null;
        try {
            result = sqlStatement.executeQuery("SELECT * FROM client WHERE name='" + clientName + "'");
            result.next();
            this.bankPassword= result.getString("passwordMarket");
            result.close();
        } catch (SQLException ex) {
            Logger.getLogger(AccountClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        return marketPassword;
    }

    @Override
    public synchronized String getBankPassword() throws RemoteException {
        ResultSet result = null;
        try {
            result = sqlStatement.executeQuery("SELECT * FROM client WHERE name='" + clientName + "'");
            result.next();
            this.bankPassword= result.getString("passwordBank");
            result.close();
        } catch (SQLException ex) {
            Logger.getLogger(AccountClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        return bankPassword;
    }
    
    @Override
    public synchronized void setBankPassword(String bankPassword) throws RemoteException {
        try {
            this.bankPassword = bankPassword;
            sqlStatement.executeUpdate("UPDATE client SET passwordBank='" + bankPassword + "' WHERE name='" + clientName + "'");
        } catch (SQLException ex) {
            Logger.getLogger(AccountClient.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }

    public synchronized Market getMarket() {
        return market;
    }
}
